<template>
  <div class="">
    <el-card v-if="contentView">
      <el-row>
        <el-col :span="4" style="margin-right: 10px">
          <!--<Searchmodule :placeholder="placeholder" @seacherKey="seacher"></Searchmodule>-->

          <el-input
            placeholder="物料编号" size="medium"
            v-model="queryInfo.materialNumber"
            clearable>
          </el-input>

        </el-col>
        <el-col :span="4" style="margin-right: 10px">
          <el-input size="medium"
            placeholder="物料描述"
            v-model="queryInfo.materialName"
            clearable>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button   type="primary" icon="el-icon-search" @click="seacher">搜索</el-button>
        </el-col>

        <el-col :span="12" style="text-align: right;">
          <div style="display: flex;justify-content:flex-end;">
<!--            <el-button v-if="authFilter('down_materail_template')" type="primary" icon="el-icon-download" :loading="isDown" @click="downloadMaterailTemplate">下载导入模板</el-button>-->
            <!--<el-upload   style="margin: 0 10px;" action="http://47.106.202.170:10084/material/basicInfo/importMaterail"-->
                         <!--:on-success="uploadSuccessHandler"-->
                         <!--:on-error="uploadFailHandler"-->
                         <!--:before-upload="beforeUpload"-->
                         <!--name="excel" :show-file-list="false" :headers="headers">-->
              <!--<el-button v-if="authFilter('import_materail')" type="primary" icon="el-icon-download">导入</el-button>-->
            <!--</el-upload>-->
            <el-button  type="primary" icon="el-icon-download" @click="downloadTemplate">下载导入模板</el-button>
            <el-button   type="primary" icon="el-icon-download" @click="addImoprt">新增导入</el-button>
            <el-button   type="primary" icon="el-icon-upload2" :loading="isExport" @click="exportData">导出</el-button>
            <!--<el-button v-if="authFilter('add_materail_info')" type="primary" icon="el-icon-plus" @click="operationView(0)">添加</el-button>-->
          </div>
        </el-col>
      </el-row>
      <!--表格-->
      <el-table :row-style="{height: '10px'}" :cell-style="{padding:'0px'}" :data="tableData" border v-loading="loading" style="width: 100%">
        <el-table-column fixed="left" prop="materialNumber" :show-overflow-tooltip="true" label="物料号码" align="center" width="180" >
        </el-table-column>
        <el-table-column fixed="left" prop="materialName" :show-overflow-tooltip="true" label="物料描述" align="center" width="180">
        </el-table-column>
        <!--<el-table-column prop="materialName" :show-overflow-tooltip="true" label="物料描述长文本" align="center" width="150">-->
        <!--</el-table-column>-->
<!--        <el-table-column prop="logisticsCode" :show-overflow-tooltip="true" label="物流编码" align="center" width="180">-->
<!--        </el-table-column>-->
        <el-table-column  prop="description" :show-overflow-tooltip="true" label="物料描述长文本"  align="center" width="150">
        </el-table-column>
        <el-table-column  prop="ypkProductFlag" label="易派客物料标识" align="center" width="150" >
      </el-table-column>
        <el-table-column  prop="ykpDownPut" label="易派客下架标识" align="center" width="150">
        </el-table-column>
        <el-table-column  prop="avgPrice" label="移动平均价格" align="center" width="150">
        </el-table-column>
        <el-table-column prop="planDeliveryDays" label="计划交货时间" align="center" width="150">
        </el-table-column>
        <el-table-column  prop="ypkPutDate" :show-overflow-tooltip="true" label="易派客上架时间" align="center" width="150">
        </el-table-column>
        <el-table-column  prop="ykpDownDate" :show-overflow-tooltip="true" label="易派客下架时间" align="center" width="150">
        </el-table-column>
        <el-table-column prop="materialGroupNumber" label="物料组编号" align="center" width="150">
        </el-table-column>
        <el-table-column prop="unit" label="计量单位" align="center" >
        </el-table-column>
        <el-table-column prop="creatorName" label="创建人" align="center" >
        </el-table-column>
        <el-table-column  label="审核状态" align="center" >
          <template slot-scope="scope">
            <span v-if="scope.row.status.code==3" @click="history(scope.row)" style="color: #1c9913;cursor: pointer;">{{scope.row.status.name}}</span>
            <span v-else-if="scope.row.status.code==2" @click="history(scope.row)" style="color: #ffb547;cursor: pointer;">{{scope.row.status.name}}</span>
            <span v-else style="color: #ff4141">{{scope.row.status.name}}</span>
          </template>
        </el-table-column>
<!--        <el-table-column  fixed="right" label="操作" align="center" width="200">-->
<!--          <template  slot-scope="scope">-->
<!--            <div  >-->
<!--              <el-button type="text" icon="el-icon-edit" @click="operationView(1, scope.row)">编辑</el-button>-->
<!--              <el-button v-if="scope.row.status.code == 2" type="text" icon="el-icon-edit" @click="withdraw(scope.row)">撤回</el-button>-->
<!--              &lt;!&ndash; <el-button type="primary" :loading="scope.row.loading" icon="el-icon-delete" @click="operationView(2, scope.row)">删除</el-button> &ndash;&gt;-->
<!--            </div>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
      <el-pagination style="text-align: center;" :disabled="loading" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="queryInfo.pageNo" :page-sizes="[25,50]" :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>
    <submitForm v-else :subData="subData" @closeView="closeView" @refresh="refreshTable"></submitForm>
    <historyLook :visible.sync="visible" :historyTables="historyTables"/>


    <el-dialog :visible.sync="importVisible" append-to-body width="30%">
      <p style="text-align: center;" class="map">新增导入</p>
      <el-form :model="importForm">
        <el-form-item label="导入的文件" prop="fileName">
          <el-upload   style="margin: 0 10px;" :action="importUrl+'import/uploadExcel'"
                       :on-success="uploadSuccessHandler"
                       :on-error="uploadFailHandler"
                       :before-upload="beforeUpload"
                       :file-list="fileList"
                       multiple
                       name="excel" :show-file-list="true" :headers="headers">
            <el-button  type="primary" icon="el-icon-download">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">上传EXCEL文件</div>
          </el-upload>

        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button class="global-button" round type="primary" @click="importVisible = false">关闭</el-button>
        <el-button class="global-button" round type="primary" @click="submitImport">提交</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import submitForm from './Material/addMaterial.vue'
  import historyLook from '@/components/historyLook'
  import { pageMaterail, exportMaterail, downloadMaterailTemplate, importMaterail } from '@/api/essentialInformation.js'
  import { getHistoryLook,postWithdraw } from '@/api/user'
  import { mapState } from "vuex";
  // import { downloadFile } from '@/utils/utils.js'
  import { applyImport,downloadTemplateByType } from '@/api/importApply.js'
  let $this = null
  export default {
    name: 'purchase',
    components: { submitForm,historyLook },
    data () {
      return {
        contentView: true,
        placeholder: '物料描述或物料编号',
        loading: false,
        queryInfo: {
          pageNo: 1,
          pageSize: 25,
          materialName: '',
          materialNumber: '',
        },
        tableData: [],
        total: 0,
        subData: {
          btnId: '',
          id: ''
        },
        fileList: [],
        headers: {
          apiKey: window.sessionStorage.getItem('token')
        },
        isDown: false,
        isExport: false,
        visible: false,
        importVisible:false,
        historyTables: [],
        importForm:{
          importType:0,
          fileName:''
        },
        importUrl:this.importUrl,
      }
    },
    created () {
      $this = this
      if(this.$route.params.id) {
        this.contentView = false
        this.subData = {
          btnId: 1,
          id: this.$route.params.id
        }
      }
      $this.getPageMaterail()
    },
    methods: {
      downloadTemplate () {
        $this.isDown = true
        const ttt={
          type:0
        }
        downloadTemplateByType(ttt).then(res => {
          $this.isDown = false
          $this.downloadFile(res,  '材料导入模板')
        }).catch(err => {
          $this.isDown = false
          return $this.$message.error('导出文件错误')
        })
      },
      addImoprt () {
        this.importVisible = true
      },
      submitImport(){
        if (!$this.importForm.fileName){
          $this.$message({
            type: 'error',
            message: '文件不能为空',
            showClose: true
          })
          return
        }
        this.$loading({
          lock: true,
          text: '正在导入...',
          spinner: 'el-icon-loading',
        })

        applyImport($this.importForm).then(res => {
          this.$loading().close()
          if (res.data.code == 500) {
            return $this.$message.error(res.data.message)
          }else {
            this.importVisible = false
            this.$message.success(res.data.message)
            $this.$emit('refresh')
          }

        })
      },
      authFilter (code) {
        let flag = false
        if(this.authList.length) {
          this.authList.forEach(item => {
            if(item.resourceCode == code) {
            flag = true
          }
        })
        }
        return flag
      },
      // 撤回
      withdraw (row) {
        this.$loading()
        postWithdraw({"documentId": row.id }).then(res => {
          this.$loading().close()
        const { data } = res
        if(data.code == "200") {
          this.getPageMaterail()
          this.$message.success(data.message)
        }else {
          this.$message.error(data.message)
        }
      })
      },
      // 审批历史
      history (row) {
        getHistoryLook(row.processInstanceId).then(res => {
          this.historyTables = res.data.data
        this.visible = true
      })
      },
      // 材料基本信息列表
      getPageMaterail () {
        $this.loading = true
        pageMaterail($this.queryInfo).then(res => {
          $this.loading = false
        $this.tableData = res.data.data.records
        $this.total = res.data.data.total
      }).catch(err => {
          $this.loading = false
        return $this.$message.error(err.message)
      })
      },
      handleCurrentChange (val) {
        $this.queryInfo.pageNo = val
        $this.getPageMaterail()
      },
      handleSizeChange (size) {
        $this.queryInfo.pageSize = size
        $this.getPageMaterail()
      },
      seacher (key) {
        $this.queryInfo.pageNo = 1

        $this.getPageMaterail()
      },

      operationView (btnId, row) {
        if (btnId === 0) {
          $this.subData.btnId = btnId
          $this.contentView = false
        } else if (btnId === 1) {
          $this.subData.btnId = btnId
          $this.subData.id = row.id
          $this.contentView = false
        } else {
          return $this.$message.error('操作错误')
        }
      },
      // 返回table
      closeView () {
        $this.contentView = true
      },
      refreshTable () {
        $this.getPageMaterail()
        $this.contentView = true
      },
      // 下载导入模板
      // downloadMaterailTemplate () {
      //   $this.isDown = true
      //   downloadMaterailTemplate().then(res => {
      //     $this.isDown = false
      //   $this.downloadFile(res, '导入模板')
      // }).catch(err => {
      //     $this.isDown = false
      //   return $this.$message.error('导出文件错误')
      // })
      // },
      // 导入成功触发
      beforeUpload(file) {
        this.$loading({
          lock: true,
          text: '正在上传...',
          spinner: 'el-icon-loading',
        })
      },
      // 导入成功触发
      uploadSuccessHandler (response, file, fileList) {
        this.$loading().close()
        if (response.success) {
          $this.$message({
            type: 'success',
            message: '上传成功,请提交审批',
            showClose: true
          })
          $this.importForm.fileName=response.data.fileName
          $this.importForm.originFileName=response.data.originFileName
          $this.fileList=[]
          $this.fileList.push({name:response.data.originFileName,url:''})
          // this.getPageProcurement()
        } else {
          $this.$message({
            type: 'error',
            message: response.message,
            showClose: true
          })
          $this.fileList=[]
        }
      },
      uploadFailHandler () {
        this.$loading().close()
        $this.$message.error('上传失败')
      },
      // 导出
      exportData () {
        $this.isExport = true
        exportMaterail($this.queryInfo)
          .then((res) => {
          $this.isExport = false
        $this.downloadFile(res, '材料基础信息表')
      })
      .catch((err) => {
          $this.isExport = false
        return $this.$message.error('导出文件错误')
      })
      },
      downloadFile (res, name) {
        const blob = new Blob([res.data])
        const fileName = name + '.xlsx'
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      }
    },
    computed: {
      ...mapState(["authList"]),
  }
  }
</script>

<style lang="scss" scoped>

</style>
